package com.runen.infinitemovement.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.ColumnActivityNameAdapter;
import com.runen.infinitemovement.adapter.MyActivityAdapter;
import com.runen.infinitemovement.adapter.MyDynamicStateAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.ActivitiesEntity;
import com.runen.infinitemovement.model.entity.MyHomeEntity;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.CustomLoadMoreView;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyHomeActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.iv_bg)
    ImageView ivBg;
    @BindView(R.id.btn_finish)
    Button btnFinish;
    @BindView(R.id.iv_add_focus)
    ImageView ivAddFocus;
    @BindView(R.id.tv_add_focus)
    TextView tvAddFocus;
    @BindView(R.id.ll_focus)
    LinearLayout llFocus;
    @BindView(R.id.iv_add_like)
    ImageView ivAddLike;
    @BindView(R.id.tv_add_like)
    TextView tvAddLike;
    @BindView(R.id.ll_like)
    LinearLayout llLike;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_describe)
    TextView tvDescribe;
    @BindView(R.id.tv_sports_num)
    TextView tvSportsNum;
    @BindView(R.id.tv_distance_km)
    TextView tvDistanceKm;
    @BindView(R.id.tv_like_num)
    TextView tvLikeNum;
    @BindView(R.id.rv_column_activity)
    RecyclerView rvColumnActivity;
    @BindView(R.id.rv_column_activity_list)
    RecyclerView rvColumnActivityList;
    @BindView(R.id.rv_my_status_list)
    RecyclerView rvMyStatusList;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.rci_user_header)
    RoundedCornersImage rciUserHeader;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.ll_add_focus_like)
    LinearLayout llAddFocusLike;
    @BindView(R.id.rl_header)
    RelativeLayout rl_header;
    private ColumnActivityNameAdapter columnActivityNameAdapter;
    private String[] columnTypeNames = new String[]{"参与活动", "动态"};
    private List<String> columnList = new ArrayList<>();
    private MyActivityAdapter myActivityAdapter;
    private MyDynamicStateAdapter myDynamicStateAdapter;
    private String userId;
    private MyHomeEntity.DataBean dataBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_my_home;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        NotchTools.getFullScreenTools().translucentStatusBar(this, new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) ivBg.getLayoutParams();
                lp.height = CommonUtil.dp2px(MyHomeActivity.this, 172) + CommonUtil.getStatusBarHeight(MyHomeActivity.this);
                ivBg.setLayoutParams(lp);
                RelativeLayout.LayoutParams lp1 = (RelativeLayout.LayoutParams) btnFinish.getLayoutParams();
                lp1.topMargin = btnFinish.getTop() + CommonUtil.getStatusBarHeight(MyHomeActivity.this);
                btnFinish.setLayoutParams(lp1);
                RelativeLayout.LayoutParams lp2 = (RelativeLayout.LayoutParams) rl_header.getLayoutParams();
                lp2.topMargin = CommonUtil.dp2px(MyHomeActivity.this, 130) + CommonUtil.getStatusBarHeight(MyHomeActivity.this);
                rl_header.setLayoutParams(lp2);
            }
        });
        userId = getIntent().getStringExtra("userId");
        if (UserAPI.getUserId().equals(userId)) {
            llAddFocusLike.setVisibility(View.INVISIBLE);
        } else {
            llAddFocusLike.setVisibility(View.VISIBLE);
        }
        srl.setOnRefreshListener(this);
        LinearLayoutManager layoutManager2 = new GridLayoutManager(this, 2);
        rvColumnActivity.setLayoutManager(layoutManager2);
        columnActivityNameAdapter = new ColumnActivityNameAdapter(this);
        rvColumnActivity.setAdapter(columnActivityNameAdapter);
        columnList.clear();
        for (int i = 0; i < columnTypeNames.length; i++) {
            columnList.add(columnTypeNames[i]);
        }
        columnActivityNameAdapter.setNewData(columnList);

        /**
         * 参与活动
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        rvColumnActivityList.setLayoutManager(layoutManager);
        myActivityAdapter = new MyActivityAdapter(this);
        rvColumnActivityList.setAdapter(myActivityAdapter);

        myActivityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(MyHomeActivity.this, MyTheLongMarchRoadActivity.class);
                intent.putExtra("userId", userId);
                startActivity(intent);
            }
        });
        /**
         * 动态
         */
        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(RecyclerView.VERTICAL);
        rvMyStatusList.setLayoutManager(layoutManager1);
        myDynamicStateAdapter = new MyDynamicStateAdapter(this, 1);
        myDynamicStateAdapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
        rvMyStatusList.setAdapter(myDynamicStateAdapter);

        columnActivityNameAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                columnActivityNameAdapter.setCheckPosition(position);
                columnActivityNameAdapter.notifyDataSetChanged();
                initColumnTypeName(position);
            }
        });
        initColumnTypeName(0);
        initData();
    }

    private void initData() {
        srl.setRefreshing(true);
        String str = "?userId=%s";
        new UserAPI().getMyHome(String.format(str, userId), new BaseResultCallback<MyHomeEntity>() {
            @Override
            public void onResponse(MyHomeEntity response) {
                srl.setRefreshing(false);
                if (response.code == 0) {
                    if (response.data != null) {
                        dataBean = response.data;
                        if (dataBean.isConcerned) {
                            llFocus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ffd7d7d7_stroke_360dp));
                            tvAddFocus.setText("取消关注");
                            ivAddFocus.setVisibility(View.GONE);
                            tvAddFocus.setTextColor(CommonUtil.getColor(R.color.color_FF666666));
                        } else {
                            llFocus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ee4238_df2526_360dp));
                            tvAddFocus.setText("关注");
                            ivAddFocus.setVisibility(View.VISIBLE);
                            tvAddFocus.setTextColor(CommonUtil.getColor(R.color.white));
                        }
                        if (dataBean.isLike) {
                            tvAddLike.setText("已赞");
                            llLike.setBackground(CommonUtil.getDrawable(R.drawable.bg_fff63e5a_storke_360));
                            ivAddLike.setImageResource(R.mipmap.ico_like);
                            tvAddLike.setTextColor(CommonUtil.getColor(R.color.color_FFF63E5A));
                        } else {
                            tvAddLike.setText("点赞");
                            llLike.setBackground(CommonUtil.getDrawable(R.drawable.bg_ee4238_df2526_360dp));
                            ivAddLike.setImageResource(R.mipmap.ico_priase_white);
                            tvAddLike.setTextColor(CommonUtil.getColor(R.color.white));
                        }
                        if (!TextUtils.isEmpty(dataBean.cover)) {
                            GlideUtils.loadImage(MyHomeActivity.this, dataBean.cover, ivBg);
                        }
                        if (!TextUtils.isEmpty(dataBean.headImgUrl)) {
                            GlideUtils.loadImage(MyHomeActivity.this, dataBean.headImgUrl + "?x-oss-process=image/resize,m_fill,w_144,h_144", rciUserHeader);
                        }

                        tvUserName.setText(dataBean.nickname);
                        if (!TextUtils.isEmpty(dataBean.introduction)) {
                            tvDescribe.setText(dataBean.introduction);
                        } else {
                            if (UserAPI.getUserId().equals(userId)) {
                                tvDescribe.setEnabled(true);
                                tvDescribe.setText("你还没有填写个人简介，点击添加…");
                            } else {
                                tvDescribe.setText("他还没有填写个人简介");
                                tvDescribe.setEnabled(false);
                            }
                        }
                        tvDistanceKm.setText(String.valueOf(dataBean.sportDistance));
                        tvSportsNum.setText(String.valueOf(dataBean.sportCounts));
                        tvLikeNum.setText(String.valueOf(dataBean.sportLikeCounts));
                        if (null != dataBean.myEnterActivities) {
                            if (dataBean.myEnterActivities.myEnterActivitiesDto != null) {
                                dataBean.myEnterActivities.myEnterActivitiesDto.flag = 1;
                                List<ActivitiesEntity> activitiesEntities = new ArrayList<>();
                                activitiesEntities.add(dataBean.myEnterActivities.myEnterActivitiesDto);
                                myActivityAdapter.setNewData(activitiesEntities);
                            } else if (null != dataBean.myEnterActivities.myEnterActivitiesDtoList) {
                                if (dataBean.myEnterActivities.myEnterActivitiesDtoList.size() > 0) {
                                    myActivityAdapter.setNewData(dataBean.myEnterActivities.myEnterActivitiesDtoList);
                                }
                            }
                        }
                        if (null != dataBean.myDynamics) {
                            if (dataBean.myDynamics.size() > 0) {
                                myDynamicStateAdapter.setNewData(dataBean.myDynamics);
                            }
                        }
                    }
                }
            }
        });
    }

    private void initColumnTypeName(int position) {
        if (position == 0) {
            rvColumnActivityList.setVisibility(View.VISIBLE);
            rvMyStatusList.setVisibility(View.GONE);
        } else {
            rvColumnActivityList.setVisibility(View.GONE);
            rvMyStatusList.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }


    @Override
    public void onRefresh() {
        initData();
    }

    @OnClick({R.id.btn_finish, R.id.ll_focus, R.id.ll_like, R.id.tv_describe, R.id.rci_user_header})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_finish:
                finish();
                break;
            case R.id.ll_focus:
                if (null != dataBean) {
                    if (dataBean.isConcerned) {
                        dataBean.isConcerned = false;
//                        tvAddFocus.setText("取消关注");
//                        ivAddFocus.setVisibility(View.GONE);
//                        tvAddFocus.setTextColor(CommonUtil.getColor(R.color.color_FF666666));
//                        llFocus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ffd7d7d7_stroke_360dp));
                        onCancelFocus();
                    } else {
                        dataBean.isConcerned = true;
//                        tvAddFocus.setText("关注");
//                        ivAddFocus.setVisibility(View.VISIBLE);
//                        tvAddFocus.setTextColor(CommonUtil.getColor(R.color.white));
//                        llFocus.setBackground(CommonUtil.getDrawable(R.drawable.bg_ee4238_df2526));
                        addFocus();
                    }
                }
                break;
            case R.id.ll_like:
                if (dataBean != null) {
                    if (dataBean.isLike) {
//                        llLike.setBackground(CommonUtil.getDrawable(R.drawable.bg_fff63e5a_storke_360));
                        dataBean.isLike = false;
//                        tvAddLike.setText("已赞");
//                        ivAddLike.setImageResource(R.mipmap.ico_like);
//                        dataBean.sportLikeCounts--;
//                        tvAddLike.setTextColor(CommonUtil.getColor(R.color.color_FFF63E5A));
                    } else {
                        llLike.setBackground(CommonUtil.getDrawable(R.drawable.bg_ee4238_df2526_360dp));
                        dataBean.isLike = true;
//                        tvAddLike.setText("点赞");
//                        ivAddLike.setImageResource(R.mipmap.ico_priase_white);
//                        tvAddLike.setTextColor(CommonUtil.getColor(R.color.white));
//                        dataBean.sportLikeCounts++;
                    }
//                    tvLikeNum.setText(String.valueOf(dataBean.sportLikeCounts));
                    onLike(dataBean.isLike);
                }
                break;
            case R.id.tv_describe:
                Intent intent = new Intent(this, EditUserInfoActivity.class);
                intent.putExtra("TITlE_NAME", "个性签名");
                intent.putExtra("input_info", "请输入个性签名");
                startActivityForResult(intent, 99);
                break;
            case R.id.rci_user_header:
                if (dataBean != null && !TextUtils.isEmpty(dataBean.headImgUrl)) {
                    ArrayList<String> list = new ArrayList<>();
                    list.add(dataBean.headImgUrl);
                    Intent intent1 = new Intent(this, PhotoActivity.class);
                    intent1.putExtra("position", 0);
                    intent1.putStringArrayListExtra("list", list);
                    startActivity(intent1);
                }
                break;
        }
    }

    private void onLike(boolean isLike) {
        JSONObject object = new JSONObject();
        try {
            object.put("likeDataId", userId);
            object.put("toLikeUserId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().userAddOrCancelLike(isLike, object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {
                ToastUtils.showShort(response.getMessage());
                initData();
            }
        });
    }


    /**
     * 关注
     *
     * @param
     */
    private void addFocus() {
        JSONObject object = new JSONObject();
        try {
            object.put("concernedUserId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().addFocus(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                ToastUtils.showShort("关注成功");
                initData();
            }
        });

    }

    /**
     * 取消关注
     *
     * @param
     */
    private void onCancelFocus() {
        JSONObject object = new JSONObject();
        try {
            object.put("unConcernedUserId", userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().cancelFocus(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                ToastUtils.showShort("取消关注成功");
                initData();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 99) {
            if (data != null) {
                String userSignature = data.getStringExtra("USER_SIGNATURE");
                if (!TextUtils.isEmpty(userSignature)) {
                    tvDescribe.setText(userSignature);
                }
            }
        }
    }
}
